package com.phery.minicap;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;

public class InitDevices
{
	public static int SDK_VERSION;
	public static String ABI;
	public static int PRE;
	public static String REL;
	public static String DIR;
	public static String BIN;

	public static void init()
	{
		SDK_VERSION = Integer.valueOf(excuteCommand("adb shell getprop ro.build.version.sdk")).intValue();
		ABI = excuteCommand("adb shell getprop ro.product.cpu.abi");
		String preSDK = excuteCommand("adb shell getprop ro.build.version.preview_sdk");
		if (!"".equals(preSDK))
			PRE = Integer.valueOf(preSDK).intValue();
		REL = excuteCommand("adb shell getprop ro.build.version.release");
		DIR = "/data/local/tmp/minicap-devel";
		if (PRE > 0)
			SDK_VERSION++;
		if (SDK_VERSION >= 16)
			BIN = "minicap";
		else
			BIN = "minicap-nopie";
		String result;
		result = excuteCommand("adb shell \"mkdir " + DIR + " 2>/dev/null || true\"");
		System.out.println(result);
		result = excuteCommand("adb push resource/libs/" + ABI + "/" + BIN + " " + DIR);
		System.out.println(result);
		result = excuteCommand("adb push resource/aosp/libs/android-" + SDK_VERSION + "/" + ABI + "/minicap.so " + DIR);
		System.out.println(result);
		result = excuteCommand("adb shell \"chmod 777 " + DIR + "/*\"");
		System.out.println(result);
		result = excuteCommand("adb forward tcp:1717 localabstract:minicap");
		System.out.println(result);

		String wmsize = excuteCommand("adb shell wm size");
		String[] value = wmsize.split(" ");
		wmsize = value[2];

		try
		{
			Runtime.getRuntime().exec(
					"adb shell LD_LIBRARY_PATH=" + DIR + " " + DIR + "/" + BIN + " -Q 100 -P " + wmsize + "@480x800/0");
		} catch (IOException e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		// System.out.println(result);

	}

	// public static void main(String[] args)
	// {
	// init();
	// }

	public static String excuteCommand(String cmd)
	{
		/* 获取cmd命令 */
		try
		{
			System.out.println("正在执行命令：" + cmd);
			Process pro = Runtime.getRuntime().exec(cmd); // 添加要进行的命令，"cmd
															// /c
															// calc"中calc代表要执行打开计算器，如何设置关机请自己查找cmd命令

			BufferedReader br = new BufferedReader(new InputStreamReader(pro.getInputStream())); // 虽然cmd命令可以直接输出，但是通过IO流技术可以保证对数据进行一个缓冲。
			String msg = null;
			String result = null;
			System.out.println("执行完成！！！");
			while ((msg = br.readLine()) != null)
			{
				System.out.println(msg);
				if (result == null)
					result = msg;
			}
			System.out.println(result);
			return result;
		} catch (IOException exception)
		{
			exception.printStackTrace();
			return "";
		}

		/*
		 * cmd /c dir 是执行完dir命令后关闭命令窗口 cmd /k dir 是执行完dir命令后不关闭命令窗口 cmd /c start
		 * dir 会打开一个新窗口后执行dir命令，原窗口会关闭 cmd /k start dir 会打开一个新窗口后执行dir命令，原窗口不会关闭
		 * cmd /? 查看帮助信息
		 */

	}

}
